﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HtmlAgilityPack;
using GeneCMS.Models.physical;
using System.Text;

namespace GeneCMS.Models.Helpers
{
    public static class ContentRendererHelper
    {
        public static string AddContentEditsToPage(int page_id, IEnumerable<Content> page_contents)
        {
            StringBuilder html = new StringBuilder("<script type=\"text/javascript\">");
           
            foreach (var content in page_contents)
            {
                html.AppendLine();
                html.Append("_contents_hash[\"");
                html.Append(content.AttributeToMatch.Trim() ?? "id");
                html.Append("='");
                html.Append(content.ElementMatchCriteria);
                html.Append("'\"] = {");

                html.Append("\"ID\":\"");
                html.Append(content.ID);
                html.Append("\",  ");
                html.Append("\"PageID\":\"");
                html.Append(content.PageID);
                html.Append("\",  ");
                html.Append("\"ElementMatchCriteria\":\"");
                html.Append(content.ElementMatchCriteria);
                html.Append("\", ");
                html.Append("\"AttributeToMatch\":\"");
                html.Append(content.AttributeToMatch);
                html.Append("\", ");
                html.Append("\"Html\":\"");
                html.Append(content.Html.EscapeJS());
                html.Append("\".replace( /GENESCPT/gm,\"script>\") , ");
                html.Append("\"Title\":\"");
                html.Append(content.Title.EscapeJS());
                html.Append("\" }");
            }
            html.AppendLine();
            html.Append("_page_id=");
            html.Append(page_id);
            html.Append("</script>");
            return html.ToString();
        }

        public static string EscapeJS(this string str)
        {
            return str.Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "").Replace("script>", "GENESCPT"); ;
        }
    }
}
